package com.sola.mybatis.service.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.sola.mybatis.entity.User;
import com.sola.mybatis.mapper.UserMapper;
import com.sola.mybatis.service.IUserService;

@Service
public class UserService implements IUserService{
	
	private static final Logger logger=LoggerFactory.getLogger(UserService.class);


	@Autowired
	private RedisTemplate redisTemplate;
	
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public int add(User user) {
		return userMapper.add(user);
	}

	/**
	 * 
	 * @param accout
	 * @return
	 * 更新Account逻辑
	 * 如果缓存存在，删除
	 * 如果不存在，不用操作
	 * 
	 */
	@Override
	public int update(User user) {
		String key = "User_" + user.getId();
		//缓存存在
		boolean haskey=redisTemplate.hasKey(key);
		if(haskey){
			logger.info("update():删除User缓存"+user.toString());
			redisTemplate.delete(key);
		}
		return userMapper.update(user);
	}

	@Override
	public int delete(String id) {
		return userMapper.delete(id);
	}

	/**
	 * 
	 * @param id
	 * 如果缓存存在，从缓存中获取信息
	 * 如果不存在，从数据库里面获取，然后插入缓存
	 */
	@Override
	public User getUserById(String id) {
		
		String key="User_"+id;
		ValueOperations<String,User> operations=redisTemplate.opsForValue();
		//缓存存在
		boolean haskey=redisTemplate.hasKey(key);
		if(haskey){
			User user = operations.get(key);
			logger.info("getUserById():获取缓存"+user.toString());
			return  user;
		}
		//从数据库里面获取Account信息
		User user= userMapper.getUserById(id);
		//插入缓存  10代表 缓存有效时间 为10秒
		operations.set(key, user,10,TimeUnit.HOURS);
		logger.info("getUserById():插入缓存"+user.toString());
		return user;
	}

	@Override
	public List<User> getUserList() {
		return userMapper.getUserList();
	}

}
